//
//  RequestManager.m
//  片刻
//
//  Created by admin on 15/6/4.
//  Copyright (c) 2015年 iApple. All rights reserved.
//

#import "RequestManager.h"
#import "AppDelegate.h"

@implementation RequestManager

- (void)dealloc
{
    [_data release];
    [_parameterDic release];
    [super dealloc];
}

- (instancetype) initWithRequestURL:(NSString *)urlString requestModel:(RequestModel )requestModel requestParameter:(NSString *)parameter {
    self = [super init];
    if (self) {
        _requestURL = urlString;
        _requestModel = requestModel;
        _requestParameter = parameter;
        _parameterDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    return self;
}

//开始请求
- (void)startRequest {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSURL *url = [NSURL URLWithString:_requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (_requestModel == POST) {
        [self parameterDicToString];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)parameterDicToString {
    if (_parameterDic.count != 0) {
        NSMutableArray *parameterArray = [NSMutableArray array];
        for (NSString *key in _parameterDic) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameterDic[key]];
            [parameterArray addObject:str];
        }
        _requestParameter = [parameterArray componentsJoinedByString:@"&"];
    }
}

#pragma mark - 代理方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_data appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:)]) {
        [_delegate requestDidFinishWithData:_data];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        [_delegate requestError:error];
    }
}

@end
